
package com.zcp.pcsuitall.business;

import com.zcp.pcsuitall.Action;
import com.zcp.pcsuitall.BusinessControl;
import com.zcp.pcsuitall.IDealWithMessage;
import com.zcp.pcsuitall.SocketService;
import com.zcp.pcsuitall.XmlDataDealWith;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.nio.channels.SocketChannel;

public class FileManager implements IDealWithMessage {

    @Override
    public boolean dealWith(SocketChannel sc, Action action, Context context) {
        Log.i("222", "LoadFile begin");
        if (action != null) {
            if ("LoadFile".equals(action.getName())) {

                String path = XmlDataDealWith.getRegularSingle("filePath", action.getSource());
                String key = XmlDataDealWith.getRegularSingle("key", action.getSource());
                Log.i("222", "path" + path);
                boolean success=returnFile(path,context,key);
                StringBuffer sb = new StringBuffer();
                sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>LoadFile</action><data>");
                sb.append("<result>"+success+"</result>");
                sb.append("</data></root>");
                BusinessControl.returnToClient(sc, sb.toString(), context);
            } else if("GetSdcardFileName".equals(action.getName()))
            {
                String dir = XmlDataDealWith.getRegularSingle("dir", action.getSource());
                readSdcardFileName(sc,context,dir);
            }else if("StartDataPort".equals(action.getName()))
            {
                String key = XmlDataDealWith.getRegularSingle("key", action.getSource());
                boolean success=startOther(context,key);
                StringBuffer sb = new StringBuffer();
                sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>StartDataPort</action><data>");
                sb.append("<result>"+success+"</result>");
                sb.append("</data></root>");
                BusinessControl.returnToClient(sc, sb.toString(), context);
            }else if("StopDataPort".equals(action.getName()))
            {
                String key = XmlDataDealWith.getRegularSingle("key", action.getSource());
                boolean success=stopOther(context,key);
                StringBuffer sb = new StringBuffer();
                sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>StopDataPort</action><data>");
                sb.append("<result>"+success+"</result>");
                sb.append("</data></root>");
                BusinessControl.returnToClient(sc, sb.toString(), context);
            }            
            else if("SaveFile".equals(action.getName()))
            {
                String key = XmlDataDealWith.getRegularSingle("key", action.getSource());
                String fileName = XmlDataDealWith.getRegularSingle("fileName", action.getSource());
                String fileLength = XmlDataDealWith.getRegularSingle("fileLength", action.getSource());
                String id = XmlDataDealWith.getRegularSingle("id", action.getSource());
                long length=Long.valueOf(fileLength);
                saveFile(length,fileName,context,key,id);
            } if ("CheckLoadFile".equals(action.getName())) {
                //先询问文件是否存在
                String path = XmlDataDealWith.getRegularSingle("filePath", action.getSource());
                readyUpLoad(sc,path,context);
            }else if("cancelFileTran".equals(action.getName()))
            {
                String key = XmlDataDealWith.getRegularSingle("key", action.getSource());
                boolean success=cancelFileTran(context,key);
                StringBuffer sb = new StringBuffer();
                sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>cancelFileTran</action><data>");
                sb.append("<result>"+success+"</result>");
                sb.append("</data></root>");
                BusinessControl.returnToClient(sc, sb.toString(), context);
            }
        }

        return false;
    }
    
    
    /**
     * 手机向客户端发送消息上传文字已经准备好了。
     * 
     * @param filePath
     */
    public void readyUpLoad(SocketChannel sc,String filePath,Context context) {
        boolean success = false;
        long length = 0;
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            success = true;
        }
        length = file.length();
        String message = getReadyUpLoadMessage(success, file);   
        
        BusinessControl.returnToClient(sc, message.toString(), context);
    }
    
    
    /**
     * 获取可以开始上传的指令返回消息。
     * 
     * @param ok 准备下载是否ok。
     * @param fileName
     * @param fileLength
     * @return
     */
    private String getReadyUpLoadMessage(boolean ok, File file) {
        StringBuilder returnMessage = new StringBuilder();
        returnMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        returnMessage.append("<root><action>CheckLoadFile</action><data>");
        returnMessage.append("<fileName>" + file.getName() + "</fileName>");
        returnMessage.append("<fileLength>" + file.length() + "</fileLength>"); 
        returnMessage.append("<filePath>" + file.getPath() + "</filePath>");  
        returnMessage.append("<result>" + ok + "</result>");    
        returnMessage.append("</data></root>");

        return returnMessage.toString();
    }
    private void saveFile(long length,String fileName,Context context,String key,String id)
    {
        if (context != null && (context instanceof SocketService)) {
            SocketService service = (SocketService) context;
            service.downLoadFile(fileName,length, key,id);
        }
        
    }
    
    private void readSdcardFileName(SocketChannel sc,Context context,String dir) {
        File file = new File(dir);
        StringBuffer sb = new StringBuffer();
        sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>GetSdcardFileName</action><data>");
        if (file != null) {
            for (File element : file.listFiles()) {

                if (element.exists()&&element.isFile()) {
                    sb.append("<filePath>" + element.getPath() + "</filePath>");
                    sb.append("<fileName>" + element.getName() + "</fileName>");
                    sb.append("<fileLength>" + element.length() + "</fileLength>");
                }
            }
        }
        sb.append("</data></root>");
        BusinessControl.returnToClient(sc, sb.toString(), context);
    }
    
    
    private boolean returnFile(String filePath, Context context, String key) {
            if (context != null && (context instanceof SocketService)) {
                SocketService service = (SocketService) context;
                return service.upLoad(filePath, key);
            }
            return false;

    }
    /**
     * 启用另一个传输通道。
     * @param context
     * @param key
     */
    private boolean startOther(Context context, String key) {
        if (context != null && (context instanceof SocketService)) {
            SocketService service = (SocketService) context;
            return service.startFileThread(Integer.valueOf(key));
        }
        return false;

    }
    
    /**
     * 取消当前端口好文件传输。
     * @param context
     * @param key
     */
    private boolean cancelFileTran(Context context, String key) {
        if (context != null && (context instanceof SocketService)) {
            SocketService service = (SocketService) context;
            return service.cancelFileTran(Integer.valueOf(key));
        }
        return false;

    }
    
    /**
     * 停止另一个传输通道。（ 默认8851传输通道不能被关闭。）
     * @param context
     * @param key
     */
    private boolean stopOther(Context context, String key) {
        if (context != null && (context instanceof SocketService)) {
            SocketService service = (SocketService) context;
            return service.stopFileThread(key.trim());
        }
        return false;

    }
    
    
//   /**
//     * 把文件返回给
//     * 
//     * @param sc
//     */
//    private static void readDataFromFile(SocketChannel sc, String filePath,Context context) {
//        FileInputStream fileInputStream = null;
//        FileChannel inChannel = null;
//        try {
//            fileInputStream = new FileInputStream(filePath);
//            inChannel = fileInputStream.getChannel();
//            ByteBuffer w_buff = ByteBuffer.allocate(1024);
//            while (true) {
//                int eof = inChannel.read(w_buff);
//                if (eof == -1)
//                    break;
//                w_buff.flip();
//                BusinessControl.returnToClient(sc, new String(w_buff.array()), context);
//                w_buff.clear();
//            }
//           BusinessControl.returnToClient(sc, "</root>", context);
//
//            Log.i("222", "readDataFromFile" + "</root>".getBytes().length);
//        } catch (IOException ioe) {
//            System.out.println(ioe.getMessage());
//        } finally {
//            if (fileInputStream != null) {
//                try {
//                    fileInputStream.close();
//                } catch (IOException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
//            if (inChannel != null) {
//                try {
//                    inChannel.close();
//                } catch (IOException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
//        }
//    }

}
